package com.zyf.wjy.controller;

import com.zyf.wjy.common.Result;
import com.zyf.wjy.entity.GrowthMonitor;
import com.zyf.wjy.service.CropService;
import com.zyf.wjy.service.FieldService;
import com.zyf.wjy.service.GrowthMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 生长监测控制器
 */
@Controller
@RequestMapping("/monitor")
public class GrowthMonitorController {
    
    @Autowired
    private GrowthMonitorService growthMonitorService;
    
    @Autowired
    private FieldService fieldService;
    
    @Autowired
    private CropService cropService;
    
    /**
     * 生长监测列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<GrowthMonitor> monitors = growthMonitorService.findAll();
        model.addAttribute("monitors", monitors);
        model.addAttribute("fields", fieldService.findAll());
        model.addAttribute("crops", cropService.findAll());
        return "monitor/list";
    }
    
    /**
     * 获取监测详情
     */
    @GetMapping("/detail/{id}")
    @ResponseBody
    public Result<GrowthMonitor> detail(@PathVariable Long id) {
        GrowthMonitor monitor = growthMonitorService.findById(id);
        if (monitor != null) {
            return Result.success(monitor);
        } else {
            return Result.error("监测记录不存在");
        }
    }
    
    /**
     * 新增/编辑页面
     */
    @GetMapping("/edit")
    public String edit(@RequestParam(required = false) Long id, Model model) {
        if (id != null) {
            GrowthMonitor monitor = growthMonitorService.findById(id);
            model.addAttribute("monitor", monitor);
        }
        model.addAttribute("fields", fieldService.findAll());
        model.addAttribute("crops", cropService.findAll());
        return "monitor/edit";
    }
    
    /**
     * 保存生长监测记录
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<GrowthMonitor> save(@RequestBody GrowthMonitor monitor) {
        try {
            GrowthMonitor saved = growthMonitorService.save(monitor);
            return Result.success("保存成功", saved);
        } catch (Exception e) {
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除生长监测记录
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        try {
            boolean success = growthMonitorService.deleteById(id);
            if (success) {
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
}

